﻿using Core.Framework.Model.Common;
using Core.Framework.Redis.Queue_Helper;
using Core.Framework.Util;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.ApiClient
{
    /// <summary>
    /// 项目管理权限验证
    /// </summary>
    public class ApiProjectMemberAttribute : Attribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {

            var token = context.HttpContext.Request.Headers["itool-project"].ToString();

            if (!string.IsNullOrWhiteSpace(token))
            {
                var result
                    = RedisQueueHelper.HashGet(RedisQueueHelperParameter.ApiClientByToken, token);

                if (string.IsNullOrWhiteSpace(result))
                {
                    context.Result = new JsonResult(new
                    {
                        code = CodeResult.PERMISSION_NO_ACCESS,
                        info = "没有访问权限"
                    });
                    return;
                }
                else
                {
                    var client = ((string)result).TryToEntity<ApiProjectInfo>();

                    context.HttpContext.Items.Add("ProjectInfo", client);

                }
            }
            else
            {
                context.Result = new JsonResult(new
                {
                    code = CodeResult.INTERFACE_FORBIDDEN,
                    info = "接口禁止访问"
                });
                return;
            }
        }
    }
}
